package csd.wyaiyr.com.service.impl;

import csd.wyaiyr.com.mapper.SysUserMapper;
import csd.wyaiyr.com.model.SysUser;
import csd.wyaiyr.com.utils.*;
import csd.wyaiyr.com.config.*;
import csd.wyaiyr.com.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
@Slf4j
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements SysUserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysUserMapper userMapper;



//   获取注册验证码

    @Override
    public BaseResult getRegisterCheckCode(SysUser sysUser) {
        SysUser result = userMapper.selectByPrimaryKey(sysUser.getMobilePhoneNumber());
        if(null != result){
          return BaseResult.error("该手机号已注册，请使用密码登录。") ;
        }
        // 最新手机号正则（覆盖16x/19x等新号段）
        String PHONE_REGEX = "^1(?:3\\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\\d|9[0-35-9])\\d{8}$";
        Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);
        // 验证手机号是否为空或格式不正确
        if(StringUtil.isEmpty(sysUser.getMobilePhoneNumber()+"") || !PHONE_PATTERN.matcher(sysUser.getMobilePhoneNumber()+"").matches()){
            return BaseResult.error("手机号格式错误");
        }
        // 生成验证码并存入Redis，有效期10分钟
        String checkcode = DxbSmsUtils.getCHeckcode(sysUser.getMobilePhoneNumber());
        redisUtil.setEx("LOGIN_SMS_CODE："+sysUser.getMobilePhoneNumber(),checkcode,30, TimeUnit.MINUTES);
        return BaseResult.ok(checkcode);
    }


    @Override
    public BaseResult register(SysUser sysUser) {
        if(StringUtil.isEmpty(sysUser.getMobilePhoneNumber())){
            return BaseResult.error("手机号不能为空");
        }
        if(StringUtil.isEmpty(sysUser.getSalt())){
            return BaseResult.error("验证码不能为空");
        }
        String redis_checkcode = redisUtil.get("LOGIN_SMS_CODE："+sysUser.getMobilePhoneNumber());
        if(!sysUser.getSalt().equals(redis_checkcode)){
            return BaseResult.error("验证码已过期,请重新获取验证码");
        }

        //新用户注册
        SysUser result = userMapper.selectByPrimaryKey(sysUser.getMobilePhoneNumber());
        if(null == result){
            // 设置默认密码为手机号后6位
            sysUser.setPassWord(sysUser.getMobilePhoneNumber().substring(5,11));
            sysUser.setCreateTime(new Date());
            int i = userMapper.insertSelective(sysUser);
            String accesstoken = UUID.randomUUID().toString().replaceAll("\\-","");
            //封装用户信息
            HashMap<String,String> resultMap = new HashMap<>();
            resultMap.put("mobilePhoneNumber",sysUser.getMobilePhoneNumber()+"");
            resultMap.put("accesstoken",accesstoken);
            redisUtil.setEx(sysUser.getMobilePhoneNumber()+"",accesstoken,2, TimeUnit.HOURS);
            return BaseResult.ok(resultMap);
        }else{
            return BaseResult.error("该手机号已注册,请使用密码登录。");
        }
    }

    @Override
    public BaseResult login(SysUser sysUser) {

        SysUser sysUser1 = userMapper.selectByPrimaryKey(sysUser.getMobilePhoneNumber());
        if(null == sysUser1){
            return BaseResult.error("当前账户无效");
        }

        String accesstoken = "" ;
        String redistoken = redisUtil.get(sysUser.getMobilePhoneNumber());
        if(!StringUtil.isEmpty(redistoken)){
            accesstoken = redistoken ;
        }else{
            accesstoken = UUID.randomUUID().toString().replaceAll("\\-","");
        }
        //封装用户信息
        HashMap<String,String> resultMap = new HashMap<>();
        resultMap.put("mobilePhoneNumber",sysUser.getMobilePhoneNumber()+"");
        resultMap.put("accesstoken",accesstoken);
        redisUtil.setEx(sysUser.getMobilePhoneNumber()+"",accesstoken,2, TimeUnit.HOURS);
        return BaseResult.ok(resultMap);

    }



}
